package com.lagou.edu.controller;

import com.lagou.edu.common.status.ResultStatus;
import com.lagou.edu.service.IUserService;
import com.lagou.edu.vo.ResultVO;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * @author 赵虎
 * @date 2021/2/22 10:49 上午
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService iUserService;

    @PostMapping("/register/{email}/{password}/{code}")
    public ResultVO register(@PathVariable("email") String email,
                             @PathVariable("password") String password,
                             @PathVariable("code") String code) {
        log.info(" register email:{}. password:{}. code:{} ", email, password, code);
        return iUserService.register(email, password, code);
    }

    @PostMapping("/login/{email}/{password}")
    public ResultVO login(HttpServletResponse response,
                        @PathVariable String email,
                        @PathVariable String password) {
        log.info("login email:{}  password:{}", email, password);
        ResultVO result = iUserService.login(email, password);
        if (result.getStatus().equals(ResultStatus.SUCCESS.getCode())) {
            response.addHeader("lagou-token", result.getData().toString());
        }
        return result;
    }

    @GetMapping("/isRegistered/{email}")
    public boolean checkRegistered(@PathVariable("email") String email) {
        log.info("  checkRegistered  email:{} ", email);
        return iUserService.isRegistered(email);
    }

    @GetMapping("/info/{token}")
    public ResultVO getEmailByToken(@PathVariable String token) {
        log.info("getEmailByToken token:{} ", token);
        String email = iUserService.getEmailByToken(token);
        if (StringUtils.isNotBlank(email)) {
            return ResultVO.ok(email);
        }
        return ResultVO.fail(ResultStatus.ERROR_SYSTEM, "未查询到信息");
    }

    @GetMapping("/logout")
    public ResultVO logout() {
        log.info("logout");
        return ResultVO.ok();
    }

}
